import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入路由页面 reg login
import Reg from '@/views/Reg/Reg'
import Login from '@/views/Login/Login'
import Main from '@/views/Main/Main'
// 导入二级路由
import Home from '@/views/Menus/Home/Home'
import UserInfo from '@/views/Menus/User/UserInfo'
import UserAvatar from '@/views/Menus/User/UserAvatar'
import UserPwd from '@/views/Menus/User/UserPwd'
import ArtCate from '@/views/Menus/Article/ArtCate'
import ArtList from '@/views/Menus/Article/ArtList'
// 导入store
import store from '../store'
Vue.use(VueRouter)
// 配置路由页面路径
const routes = [
  { path: '/reg', component: Reg },
  { path: '/login', component: Login },
  {
    path: '/',
    component: Main,
    redirect: '/home',
    children: [
      // 一般情况下子路由不以 / 开头， 会拼接前面父路由 /home
      // 如果非要以 / 开头，则不拼接前面的父路由  /home
      { path: 'home', component: Home },
      { path: 'user-info', component: UserInfo },
      { path: 'user-avatar', component: UserAvatar },
      { path: 'user-pwd', component: UserPwd },
      { path: 'art-cate', component: ArtCate },
      { path: 'art-list', component: ArtList }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 防止路由来回切换报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
// 前置路由守卫
// 注意事项：必须调用next（） 调用
// to 到哪里去
// from 从哪里来
//  放行
router.beforeEach((to, from, next) => {
  // 如果没登录不准去首页 ,但可以去登录页 /注册页
  // 登录判断依据 ： 判断是否有token
  const token = store.state.user.token
  // //  条件1：没登录
  // // 条件2： & 3： 取得页面既不是登录也不是注册页
  // if (!token && to.path !== '/login' && to.path !== '/reg') {
  //   next('/login')
  // } else {
  //   next()
  // }
  // console.log(to)
  // 使用白名单
  const whiteList = ['/login', '/reg']
  if (!token && !whiteList.includes(to.path)) {
    // 跳转到登录也提醒用户
    Vue.prototype.$message.error('请先登录')
    next('/login')
  } else {
    next()
  }
})

export default router
